<template>
  <div id="boxContent">
    <!--    顶栏-->
    <div class="seal-top">
      <div class="btn-return">
        <el-page-header icon="ArrowLeft" content="文件签署" @back="$router.go(-1)"/>
      </div>
      <div class="btn-group" >
        <el-button type="info" >上一步</el-button>
        <template v-if="!isPdfPreview">
          <el-button type="primary" >确认提交</el-button>
        </template>
      </div>
    </div>
    <div class="page-layout-main-bar">
      <div class="page-layout-left-bar">
        <div class="left-bar" id="left-bar">
          <div class="file-select-component">
            <div class="file-select-title">文件列表</div>
            <div class="file-select-list">
              <el-tooltip effect="dark" content="2022年MathorCup高校数学建模挑战赛C题.pdf" placement="right">
                <div  class="el-tooltip file-select-option selected">
                  <el-icon><Document /></el-icon>
                  <div class="file-name">2022年MathorCup高校数学建模挑战赛C题.pdf</div>
                </div>
              </el-tooltip>
            </div>
          </div>
          <div class="widget-lib-component">
            <div class="add-widget-module">
              <div class="add-widget-module-title">控件库</div>
              <div class="add-widget-module-tips">请将控件拖动到文件区域。同一页中的控件，按住键盘ctrl键后可进行多选。</div>
              <div class="add-widget-module-list">
                <div id="leftContent" class="leftArea">
                  <template v-if="!isPdfPreview">
                    <div id="OldSeal" class="sealOld" draggable="true" @dragstart="drag">
                      <div class="pict">
                        <div class="added-widget-type-name">签署区</div>
                        <div class="added-widget-type-icon"><el-icon><EditPen /></el-icon></div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div class="pdf-render-top-bar">
        <div class="pdf-render-pager">
          <div @click.stop="prePage" class="handlePrePage"><el-icon><ArrowLeftBold /></el-icon></div>
          <div class="page1">第 {{ page }} / {{ numPages }} 页</div>
          <div @click.stop="nextPage" class="handleNextPage"><el-icon><ArrowRightBold /></el-icon></div>
          <div class="toolArea">
            <span>跳到第</span>
            <el-input size="small" v-model="inputPage" @keyup.enter.native="pageChange"/>
            <span>页</span>
          </div>
        </div>
      </div>
      <div id="contentArea" class="centerArea" @dragover="allowDrop" @drop="drop">
        <!--为克隆签章定义 dragover 和 drop 函数，是为了可以进行很小位置的移动-->
        <div id="cloneSeal" class="cloneSeal" draggable="true" @dragstart="dragClone" @dragover="allowDrop"
             @drop="drop" @dblclick="toDelete">
          <div class="pict_new">
            <div class="added-widget-type-name">签署区</div>
          </div>
          <div id="icons" class="icon" @click="deleteNode">
            <span>删除</span>
          </div>
          <div class="check-icon"><el-icon><CircleCheckFilled /></el-icon></div>
        </div>
          <VuePdf
              ref="wrapper"
              class="page"
              v-for="page in numPages"
              :key="page"
              src="https://sealzy.oss-cn-qingdao.aliyuncs.com/1652503457534.pdf"
              :page="page"
              style="margin: 0 0 0 540px;overflow-y: scroll;overflow-x: hidden;"
              :scale="1"/>
      </div>

    </div>
  </div>

</template>

<script setup>
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { VuePdf, createLoadingTask } from 'vue3-pdfjs/esm';
import '../../css/Sign/seal_use.css'
import {ArrowLeft} from '@element-plus/icons';


const page = ref(1) // 当前页
const numPages = ref(0) // 总页数
const inputPage = ref(1) // 输入的页码
const x = ref(0) //鼠标相对与div左边，上边的偏移
const y = ref(0)
const type = ref(0) // 0 原来的容器 1 克隆的容器
const positionPage = ref(1) // 最终定位
const positionX = ref(0)
const positionY = ref(0)
const isPdfPreview = ref(false) // 是否pdf预盖章成功预览模式

const pdfSrc = ref("https://sealzy.oss-cn-qingdao.aliyuncs.com/1649679994089.pdf")

/**
 * 获取 pdf 信息 （总页数）
 */
onMounted(() => {
  const loadingTask = createLoadingTask(pdfSrc.value)
  loadingTask.promise.then((pdf) => {
    numPages.value = pdf.numPages
  })
  window.addEventListener('scroll', handleScroll, true);
})

/**
 * 滚动事件 滚动时更新页码
 */
const handleScroll = () => {
  let scrollTop = getScrollTop() // 滚动高度
  let onePageHeight = getAttributeValue('page', 'height') // 单页面高度
  page.value = Math.round(scrollTop / onePageHeight) + 1
}

/**
 * 获取滚动高度
 * @returns {number}
 */
const getScrollTop = () => {
  let scroll_top = 0;
  if (document.documentElement && document.documentElement.scrollTop) {
    scroll_top = document.documentElement.scrollTop;
  } else if (document.body) {
    scroll_top = document.body.scrollTop;
  }
  return scroll_top;
}

/**
 * 滚动到固定位置
 * @param target
 * @returns {boolean}
 */
const goTo = (target) => {
  let scrollT = document.body.scrollTop || document.documentElement.scrollTop
  if (scrollT > target) {
    let timer = setInterval(function () {
      let scrollT = document.body.scrollTop || document.documentElement.scrollTop
      let step = Math.floor(-scrollT / 6);
      document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
      if (scrollT <= target) {
        document.body.scrollTop = document.documentElement.scrollTop = target;
        clearTimeout(timer);
      }
    }, 20)
  } else if (scrollT === 0) {
    let timer = setInterval(function () {
      let scrollT = document.body.scrollTop || document.documentElement.scrollTop
      let step = Math.floor(300 / 3 * 0.7);
      document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
      if (scrollT >= target) {
        document.body.scrollTop = document.documentElement.scrollTop = target;
        clearTimeout(timer);
      }
    }, 20)
  } else if (scrollT < target) {
    let timer = setInterval(function () {
      let scrollT = document.body.scrollTop || document.documentElement.scrollTop
      let step = Math.floor(scrollT / 6);
      document.documentElement.scrollTop = document.body.scrollTop = step + scrollT;
      if (scrollT >= target) {
        document.body.scrollTop = document.documentElement.scrollTop = target;
        clearTimeout(timer);
      }
    }, 20)
  } else if (target === scrollT) {
    return false;
  }
}

/**
 * 跳转上一页操作
 */
const prePage = () => {
  let tempPage = page.value;
  tempPage = tempPage > 1 ? tempPage - 1 : 1;
  page.value = tempPage;
  changeScrollTop()
}

/**
 * 跳转下一页操作
 */
const nextPage = () => {
  let tempPage = page.value;
  tempPage = tempPage < numPages.value ? tempPage + 1 : numPages.value;
  page.value = tempPage;
  changeScrollTop()
}

/**
 * 根据输入的页码跳转页面
 */
const pageChange = () => {
  let reg = /^[1-9]\d*$/
  if (!reg.test(inputPage.value)) {
    this.$message.error('请输入正确的页码')
    return
  }
  inputPage.value > numPages.value ? page.value = numPages.value : page.value = ~~inputPage.value
  inputPage.value < 1 ? page.value = 1 : page.value = ~~inputPage.value
  changeScrollTop()
}

/**
 * 根据页码变化修改页面滚动距离
 */
const changeScrollTop = () => {
  let onePageHeight = document.getElementById('contentArea').offsetHeight / numPages.value
  let scrollTo = onePageHeight * (page.value - 1)
  goTo(scrollTo)
}

/**
 * 双击展示删除
 */
const toDelete = () => {
  let iconItem = document.getElementById("icons");
  iconItem.style.opacity === 1 ? iconItem.style.opacity = 0 : iconItem.style.opacity = 1
}

/**
 * 删除节点
 */
const deleteNode = () => {
  let cloneItem = document.getElementById("cloneSeal");
  cloneItem.style.opacity = 0
  cloneItem.style.left = 0
  cloneItem.style.top = 0
}

/**
 * 允许放置在该区域
 * @param ev
 */
const allowDrop = (ev) => {
  ev.preventDefault();
}

/**
 * 开始拖动 原始印章
 * @param e
 */
const drag = (e) => {
  console.log(e.toElement.id)
  type.value = 0
  let sealItem = document.getElementById(e.toElement.id);
  x.value = e.clientX - sealItem.offsetLeft;
  y.value = e.clientY - sealItem.offsetTop;
}

/**
 * 开始拖动 修改克隆印章的位置
 * @param e
 */
const dragClone = (e) => {
  // 获取侧边栏菜单宽度
  let menuWidth = document.querySelector('.page-layout-left-bar').offsetWidth
  //let menuWidth = 20

  type.value = 1
  let scrollTop = getScrollTop() // 滚动高度
  let cloneItem = document.getElementById("cloneSeal");
  x.value = e.clientX - cloneItem.offsetLeft - menuWidth;
  y.value = e.clientY - (cloneItem.offsetTop - scrollTop) - 84;
  let iconItem = document.getElementById("icons");
  iconItem.style.opacity = 1
  cloneItem.style.opacity = 1
  // console.log('-------------------------')
  // console.log('鼠标---'+ e.clientX, e.clientY )
  // console.log('签章----'+cloneItem.offsetLeft, cloneItem.offsetTop-scrollTop )
  // console.log('偏差值----'+this.x, this.y )
  // console.log('-------------------------')
  // console.log('-------------------------')
  // console.log('-------------------------')
  // console.log('-------------------------')
}

/**
 * 结束移动
 * @param ev
 */
const drop = (ev) => {
  ev.preventDefault();
  let scrollTop = getScrollTop() // 滚动高度
  let cloneItem = document.getElementById('cloneSeal') // 克隆印章
  // let leftWidth = document.getElementById('left-bar').offsetWidth // 左边区域的宽度
  let leftWidth = 540; //pdf左侧到浏览器左边的距离
  let sealWidth = document.getElementById('cloneSeal').offsetWidth // 印章宽度
  let contentWidth = document.getElementById('vue-pdf-page-1').offsetWidth // 文章的宽度
  let contentHeight = document.getElementById('vue-pdf-page-1').offsetHeight // 文章的高度
  let moveX = ev.clientX - x.value; // 印章距离浏览器左边距离
  let moveY = ev.clientY - y.value; // 印章距离浏览器顶部距离
  // 计算印章距离当前页面的左右边距
  let pageMargin = getAttributeValue('page', 'marginBottom') // 页面边距
  let pageHeight = getAttributeValue('page', 'height') // 页面高度
  let page = parseInt((moveY + scrollTop) / ((pageHeight + pageMargin))) + 1 // 第几页
  let formula = (moveY + scrollTop) - (pageHeight + pageMargin) * (page - 1) // 公式计算出距离当前页面的顶部距离

  // 获取侧边栏菜单宽度
  let menuWidth = document.querySelector('.page-layout-left-bar').offsetWidth
  //let menuWidth = 20
  // 禁止印章放在 pdf 内容外部
  let isInRight = moveX + sealWidth + 40<= contentWidth + leftWidth; // 印章是否在pdf右侧内(图示印章宽度是100，后端生成的印章宽度为400)
  let isInLeft = moveX >= leftWidth + 40; // 印章是否在pdf左侧外 （40是安全距离）
  let isInTop = moveY >= sealWidth + 180; //印章是否在该页顶部下方 （180是安全距离）
  if (isInRight && isInLeft && isInTop) {
    cloneItem.style.opacity = 1
    cloneItem.style.left = (moveX - menuWidth) + 'px'
    cloneItem.style.top = (moveY + scrollTop - 84) + 'px'  // 84是面包屑高度
    positionX.value = moveX - leftWidth
    positionY.value = formula
    positionPage.value = page // 最终页码
    console.log(positionPage.value, positionX.value, positionY.value)
  }
  cloneItem.style.opacity = 1
}

/**
 * 获取节点的某个属性值 只适用于获取 px 相关数据
 * @param className
 * @param attr
 * @returns {number}
 */
const getAttributeValue = (className, attr) => {
  let pageDiv = document.querySelector('.' + className);
  let attrsValue = getComputedStyle(pageDiv);
  let attrVal = attrsValue[attr]
  return Number(attrVal.substr(0, attrVal.length - 2)) // 截取掉 px
}

</script>

<style scoped>
#boxContent {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  width: 100%;
  min-height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
}
/deep/ .el-button--info{
  color: #fff;
  font-size: 14px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-color: transparent;
  border-color: #fff;
  border-radius: 3px;
}
/deep/ .el-button{
  width: 88px;
  margin: 0 12px;
}
/deep/ .el-button--info:hover{
  background-color: #0975e1;
  border-color: #0975e1;
}
/deep/ .el-button--primary{
  color: #fff;
  font-size: 14px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-color: #0975e1;
  border-color: #0975e1;
  border-radius: 3px;
}
.page-layout-main-bar {
  margin-top: 60px;
  width: 100%;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  overflow: hidden;
  background-color: #fff;
}

.page-layout-left-bar{
  height: 100%;
}
.left-bar{
  position: fixed;
  width: 240px;
  height: 100%;
  z-index: 998;
  padding-top: 30px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  border-right: 1px solid #e4e4e4;
  background-color: #fff;
}
.file-select-component {
  padding-bottom: 24px;
  border-bottom: 1px solid #e4e4e4;
}
.file-select-title {
  color: #333;
  font-size: 14px;
  font-weight: 500;
  padding-left: 15px;
}
.file-select-list{
  max-height: 160px;
  overflow-y: auto;
  margin-top: 15px;
}
.file-select-option.selected, .file-select-option:hover {
  background-color: #f2f2f2;
}
.file-select-option{
  width: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  padding: 0 9px 0 17px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 40px;
  line-height: 1.2;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  cursor: pointer;
}
.file-name {
  margin: 0 8px;
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  color: #4d4d4d;
  font-size: 14px;
}
.widget-lib-component{
  overflow: auto; height: 100%;
}
.add-widget-module {
  padding-bottom: 120px;
}
.add-widget-module-title{
  color: #333;
  font-size: 14px;
  font-weight: 500;
  margin-top: 25px;
  padding-left: 15px;
}
.add-widget-module-tips {
  padding: 5px 15px;
  color: #666;
  font-size: 12px;
  line-height: 20px;
}

.add-widget-module-list{
  margin-top: 23px;
  padding-left: 15px;
}

.leftArea {
  flex: 1;
  background-color: #ccc;
}
.sealOld {
  position: fixed;
  top: 290px;
  left: 15px;
}
.sealOld2 {
  position: fixed;
  top: 340px;
  left: 15px;
}
.sealOld3 {
  position: fixed;
  top: 390px;
  left: 15px;
}
.sealOld4 {
  position: fixed;
  top: 440px;
  left: 15px;
}
.sealOld5 {
  position: fixed;
  top: 490px;
  left: 15px;
}
.pict{
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 210px;
  height: 28px;
  padding: 0 16px 0 10px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  border-radius: 3px;
  border: 1px dashed rgba(0,0,0,.3);
  margin-top: 15px;
  cursor: grab;
}
.added-widget-type-name{
  font-size: 12px;
  color: #333;
  line-height: 1.2;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.added-widget-type-icon{
  color: #999;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
}

.note {
  width: 180px;
  font-size: 14px;
  background-color: #909399;
  color: #fff;
  padding: 5px;
  position: fixed;
  top: 40%;
  left: 14%;
}

.cloneSeal {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 998;
  cursor: pointer;
}
.cloneSeal:hover .icon{
  opacity: 1;
}
.pict_new{
  width: 100px;
  height: 100px;
  left: 396px;
  top: 147px;
  display: flex;
  text-align: center;
  border-color: rgb(48, 123, 246);
  z-index: 1;
  pointer-events: auto;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  justify-content: center;
  background-color: hsla(0,0%,100%,.85);
}
.icon {
  text-align: center;
  background-color: rgba(0,0,0,.7);
  color: #fff;
  font-size: 12px;
  padding: 5px 10px;
  cursor: pointer;
  opacity: 0;
}
.check-icon{
  width: 9px;
  height: 9px;
  color: rgb(48, 123, 246);
  right: 8px;
  top: 5px;
  font-size: 12px;
  position: absolute;
}

span {
  cursor: pointer;
}
.centerArea {
  margin-top: 35px;
  background-color: #f0f2f5;
  overflow-y: scroll;
  overflow-x: hidden;
}
.pdf-render-top-bar {
  padding: 5px 0;
  position: fixed;
  width: 100%;
  margin-left: 100px;
  z-index: 900;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  background-color: #fff;
  border-bottom: 1px solid #e4e4e4;
}
.pdf-render-pager {
  color: #333;
  font-size: 14px;
  padding: 0 15px;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.handlePrePage{
  margin: 3px 0 0 0;
  cursor: pointer;
}
.page{
  text-align: center;
  min-width: 100px;
}
.handleNextPage{
  margin: 3px 0 0 0;
  cursor: pointer;
}
.toolArea {
  margin-left: 120px;
  display: flex;
  align-items: center;
  color: #333;
}
/deep/ .vue-pdf{
  display: inline-block;
  margin-right: 400px;
}


.rightArea {
  flex: 1;
  background-color: #ccc;
}
.note {
  width: 170px;
  font-size: 14px;
  background-color: #909399;
  color: #fff;
  padding: 5px;
  margin-bottom: 30px;
  /* position: fixed;
   top:30%;
   left:83%;*/
}


.toolGroup {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 50%;
  left: 87%;
  transform: translate(-50%, -50%);
}

.el-button + .el-button {
  margin-left: 0
}



.el-input {
  width: 60px;
  margin: 0 10px;
}
</style>
